<?php

class CustomerController extends Zend_Controller_Action {

    public function init() {
        $this->view->baseUrl = $this->_request->getBaseUrl();
    }

    // LogIn - Profile Page
    public function indexAction() {
        $this->view->title = "Name of the customer";
        $param = $this->getRequest()->getParams();
        if(isset($param["error"])) {
            if($param["error"] == "password")
             $this->view->error = "The two passwords are different !";
            if($param["error"] == "login")
             $this->view->error = "Login already used !";
        }
        if(isset($param["err"]))
        	$this->view->error2 = "Your login or password is incorrect.";
    }

    // Submission 
    public function registerAction() {
        $this->view->title = "Register";
        
        // Params from the form
        $param = $this->getRequest()->getParams();
        $login = $param["Login"];
        $password1 = $param["Password"];
        $password2 = $param["Password2"];
        
        // Verification of passwords
        if($password1 != $password2) {
            $this->_redirect("Customer/index/error/password");
        }
        
        $customerDB = new Application_Model_Customer; 
        
        // Login already exist ?
        if($customerDB->isExist($login)) {
            $this->_redirect("Customer/index/error/login");
        }
        
        // We save the new user
        $customerDB->addUser($login, $password1);
        
        // Session
        $id = $customerDB->login($login, $password1);
        $customerSession = new Zend_Session_Namespace('log');
        $customerSession->Customer_ID = $id; 
        $this->_redirect("Index/index");
    }

    // Login 
    public function loginAction() {
        $this->view->title = "Login";
        $customerDB = new Application_Model_Customer; 
        
        $param = $this->getRequest()->getParams();
        $login = $param["Login"];
        $password = $param["Password"];
        if(($id = $customerDB->login($login, $password)) == -1) {
           $this->_redirect("Customer/index/err/2");
        } else {
            $customerSession = new Zend_Session_Namespace('log');
            $customerSession->Customer_ID = $id; 
            $this->_redirect("Index/index");
        }
    }

    // Log out
    public function logoutAction() {
        $this->view->title = "Bye !";
        $customerSession = new Zend_Session_Namespace('log');
        $customerSession->unsetAll();
        $this->_redirect("Index/index");
    }

}

